layui.use(['admin', 'table', 'form', 'tool', 'xmSelect'], function () {
    let $ = layui.$
        , admin = layui.admin
        , setter = layui.setter
        , view = layui.view
        , table = layui.table
        , form = layui.form
        , tool = layui.tool;

    // form.render(null, 'attachmentPage');

    // 角色组管理
    table.render({
        elem: '#attachmentTable'
        , url: setter.request.domainName + '/admin/routine.attachment/index?server=true'
        , toolbar: "#attachmentToolBar"
        , defaultToolbar: setter.defaultToolbar
        , page: true
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'id', title: 'ID', sort: true}
            , {field: 'topic', title: '细目'}
            , {field: 'adminUsername', title: '上传管理员',
                templet: function(d) {
                    if(d.admin){
                        return d.admin.username;
                    }else{
                        return '';
                    }
                }
            }
            , {field: 'size', title: '大小'}
            , {field: 'mime_type', title: '类型'}
            , {field: 'url', title: '预览', templet: function (d) {
                    if(d.mime_type.indexOf('image/') > -1){
                        return '<span><img style="max-height: 60px" src="' + d.full_url + '"/></span>';
                    }else if(d.mime_type.indexOf('audio/') > -1){
                        return '<span><img style="max-height: 60px" src="../static/images/music1.png"/></span>';
                    }else{
                        return '<span><img style="max-height: 60px" src="../static/images/file1.png"/></span>';
                    }
                }, width: 100}
            , {field: 'quote', title: '上传(引用)次数'}
            , {field: 'name', title: '原始名称'}
            , {field: 'storage', title: '存储方式'}
            , {field: 'last_upload_time', title: '最后上传时间',
                templet: function(d) {
                    return tool.timestampToTime(d.last_upload_time);
                }
            }
            , {title: '操作', align: 'center', fixed: 'right', toolbar: '#attachmentTableTool', width: 160}
        ]]
        , parseData: function(res){
            let code = res.code === 1 ? 0 : res.code;
            return {
                "code": code, // 解析接口状态
                "msg": res.msg, // 解析提示文本
                "count": res.data.total, // 解析数据长度
                "data": res.data.list // 解析数据列表
            };
        }
        , text: {none: '暂无数据！'}
    });

    // 自定义工具栏
    table.on('toolbar(attachmentTable)', function (obj) {
        let type = obj.event;
        active[type] ? active[type].call(this) : '';
    })

    // 工具条
    table.on('tool(attachmentTable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('确定删除此数据？', function (index) {
                let field = {ids: obj.data.id};
                // 获取角色信息
                admin.req({
                    url: setter.request.domainName + '/admin/routine.attachment/del'
                    , data: field
                    , type: 'delete'
                    , loading: false // 是否开启加载框
                    , done: function () {
                        obj.del();
                        admin.message({
                            title: '删除成功'
                            , offset: '15px'
                            , icon: 1
                            , time: 1500
                            , callback: function () {
                            }
                        })
                    }
                })
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            admin.popup({
                title: '编辑数据'
                , area: ['500px', '750px']
                , id: 'attachment-popup-edit'
                , success: function (layero, index) {
                    let layId = this.id;
                    let field = {id: data.id};
                    // 获取角色信息
                    admin.req({
                        url: setter.request.domainName + '/admin/routine.attachment/edit'
                        , data: field
                        , type: 'get'
                        , loading: false // 是否开启加载框
                        , done: function (res) {
                            let initData = res.data.row;
                            initData['lay_index'] = index;
                            view(layId).render('routine/attachment/edit', initData).done(function () {
                                form.render(null, 'layGroup');
                            });
                        }
                    })
                }
            });
        }else if(obj.event === 'info'){
            admin.popup({
                title: '查看详情'
                , area: ['750px', '750px']
                , id: 'attachment-popup-info'
                , success: function (layero, index) {
                    let layId = this.id;
                    let field = {id: data.id};
                    // 获取角色信息
                    admin.req({
                        url: setter.request.domainName + '/admin/routine.attachment/edit'
                        , data: field
                        , type: 'get'
                        , loading: false // 是否开启加载框
                        , done: function (res) {
                            let initData = res.data.row;
                            initData['size'] = sizeToStr(initData['size']);
                            view(layId).render('routine/attachment/info', initData).done(function () {
                                form.render(null, 'layPopup');
                            });
                        }
                    })
                }
            });
        }
    });

    //开启搜索
    form.on('submit(LAYSearch)', function (data) {
        let field = data.field;
        let search = [];
        let searchArr = [];
        for (let obj in field) {
            let searchData = {};
            let objNode = $(".laySearchForm").find("input[name='" + obj + "']");
            let val = objNode.val();
            if (!val || val === 0 || val === '0') {
                continue;
            }
            searchData['field'] = obj;
            searchData['val'] = val;
            searchData['operator'] = objNode.attr("operator");
            searchData['render'] = objNode.attr("render");
            search.push(searchData);
            searchArr['search'] = search;
        }
        // 执行重载
        table.reload('attachmentTable', {
            where: searchArr
        });
    });

    let active = {
        batchDel: function () {
            let checkStatus = table.checkStatus('attachmentTable')
                , checkData = checkStatus.data // 得到选中的数据
                , ids = []; // ID

            if (checkData.length === 0) {
                return layer.msg('请选择要删除的数据');
            }
            $.each(checkData, function (i, val) {
                ids.push(val.id);
            })
            layer.confirm('确定删除选中的数据？', function (index) {
                let field = {ids: ids};
                // 获取角色信息
                admin.req({
                    url: setter.request.domainName + '/admin/routine.attachment/del'
                    , data: field
                    , type: 'delete'
                    , loading: false // 是否开启加载框
                    , done: function () {
                        table.reload('attachmentTable');
                        admin.message({
                            title: '删除成功'
                            , offset: '15px'
                            , icon: 1
                            , time: 1500
                            , callback: function () {
                            }
                        })
                    }
                })
                layer.close(index);
            });
        }
    }

    window.sizeToStr = function(size) {
        let data;
        if (size < 0.1 * 1024) { //如果小于0.1KB转化成B
            data = size.toFixed(2) + "B";
        } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
            data = (size / 1024).toFixed(2) + "KB";
        } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
            data = (size / (1024 * 1024)).toFixed(2) + "MB";
        } else { //其他转化成GB
            data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
        }
        let sizeStr = data + "";
        let len = sizeStr.indexOf("\.");
        let dec = sizeStr.slice(len + 1, 2);
        if (dec === "00") {//当小数点后为00时 去掉小数部分
            return sizeStr.substring(0, len) + sizeStr.slice(len + 3, 2);
        }
        return sizeStr;
    }
})
